package com.y2w.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {

    //@Autowired
    RabbitTemplate rabbitTemplate;
    //public MyRabbitConfig(RabbitTemplate rabbitTemplate){
    //    this.rabbitTemplate=rabbitTemplate;
    //    initRabbitTEmplate();
    //}
    @Bean
    @Primary
    public RabbitTemplate rabbitTemplate(ConnectionFactory  connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate=rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitTEmplate();
        return rabbitTemplate;
    }
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    /**
     * 定制RabbitTemplate
     */
    //@PostConstruct //对象创建完以后,执行这个方法
    public void initRabbitTEmplate(){
        //确认回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * @param correlationData 当前消息的唯一数据
             * @param ack 消息成功还是失败
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                //服务期收到了
                System.out.println("correlationData = " + correlationData + ", ack = " + ack + ", cause = " + cause);
            }
        });
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 消息没有投递给指定的队列，就触发这个回调
             * @param message 消息
             * @param replycode 回复状态码
             * @param replyText 回复文本内容
             * @param exchange 交换机
             * @param routingKey routingkey
             */
            @Override
            public void returnedMessage(Message message, int replycode, String replyText, String exchange, String routingKey) {
                //报错误，修改数据库当前消息的状态
                System.out.println("message = " + message + ", replycode = " + replycode + ", replyText = " + replyText + ", exchange = " + exchange + ", routingKey = " + routingKey);
            }
        });
    }

}
